from app import db
from datetime import datetime

class Car(db.Model):
    __tablename__ = 'cars'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    brand_id = db.Column(db.Integer, db.ForeignKey('brands.id'), nullable=False)
    model = db.Column(db.String(100))
    year = db.Column(db.Integer)
    price = db.Column(db.Float, nullable=False)
    color = db.Column(db.String(50))
    engine = db.Column(db.String(100))
    transmission = db.Column(db.String(50))
    fuel_type = db.Column(db.String(50))
    mileage = db.Column(db.Float)  # 油耗
    seats = db.Column(db.Integer)
    description = db.Column(db.Text)
    image = db.Column(db.String(255))
    stock = db.Column(db.Integer, default=0)  # 库存
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联销售记录
    sales = db.relationship('Sales', backref='car', lazy=True)
    
    def __init__(self, name, brand_id, price, **kwargs):
        self.name = name
        self.brand_id = brand_id
        self.price = price
        self.model = kwargs.get('model')
        self.year = kwargs.get('year')
        self.color = kwargs.get('color')
        self.engine = kwargs.get('engine')
        self.transmission = kwargs.get('transmission')
        self.fuel_type = kwargs.get('fuel_type')
        self.mileage = kwargs.get('mileage')
        self.seats = kwargs.get('seats')
        self.description = kwargs.get('description')
        self.image = kwargs.get('image')
        self.stock = kwargs.get('stock', 0)
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'brand_id': self.brand_id,
            'brand_name': self.brand.name if self.brand else None,
            'model': self.model,
            'year': self.year,
            'price': self.price,
            'color': self.color,
            'engine': self.engine,
            'transmission': self.transmission,
            'fuel_type': self.fuel_type,
            'mileage': self.mileage,
            'seats': self.seats,
            'description': self.description,
            'image': self.image,
            'stock': self.stock,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }